from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from starlette import status

from backend.utils.security import verify_token, get_guest_user

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login", auto_error=False)

# 获取当前认证的用户信息
async def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
    if not token:
        return get_guest_user()
    return verify_token(token)

# 要求用户认证
async def require_authenticated_user(user: dict = Depends(get_current_user))-> dict:
    if not user or user.get("role") not in["管理员", "普通用户"]:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="需要登录")
    return user

# 要求用户是管理员
async def require_admin(user: dict = Depends(get_current_user)) -> dict:
    if user.get("role") != "管理员":
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="需要管理员权限")
    return user
